package com.mq.dpca.file;

import java.io.File;
import java.io.FileInputStream;

import com.ibm.mq.MQEnvironment;
import com.ibm.mq.MQException;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import com.ibm.mq.constants.MQConstants;

/**
 * 
 * MQ�����ļ�����
 * 
 */
public class mqfilesend {
	final int BUFFER_LEN = 1024 * 1024; // ���巢���ļ��Ĵ�С

	private MQQueueManager qmgr; // ���ӵ����й�����

	private MQQueue outQueue; // �������

	private String queueName = "aa"; // �������

	private String host = "127.0.0.1"; // �������

	private int port = 1414; // �������Ķ˿ں�

	private String channel = "SYSTEM.BKR.CONFIG"; // ͨ�����

	private String qmgrName = "mm"; // ���й�����

	private MQMessage outMsg; // ������Ϣ����

	private MQPutMessageOptions pmo; // ���û�ȡ��Ϣѡ��

	private String fileName = "D:\\log.txt"; // Ҫ������Ϸ����ļ�

	/**
	 * ��ʼ��������������Ϣ
	 * 
	 * @throws Exception
	 */
	private void init() throws Exception {
		/** ����MQEnvironment �����Ա�ͻ������� */
		MQEnvironment.hostname = host;
		MQEnvironment.channel = channel;
		MQEnvironment.port = port;
		// MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY,MQC.TRANSPORT_WEBSPHERE
		// MQ);

		/* ���ӵ����й����� */
		qmgr = new MQQueueManager(qmgrName);

		/* ���ö��д�ѡ���Ա���� */
		int opnOptn = MQConstants.MQOO_OUTPUT
				| MQConstants.MQOO_FAIL_IF_QUIESCING;
		// int opnOptn = MQConstants.MQOO_OUTPUT ;

		outQueue = qmgr.accessQueue(queueName, opnOptn, null, null, null);
	}

	/**
	 * ���͵�������
	 * 
	 * @throws Exception
	 */
	public void sendMessages() throws Exception {
		/* ���÷�����Ϣѡ�� */
		pmo = new MQPutMessageOptions();
		outMsg = new MQMessage();
		FileInputStream fis = new FileInputStream(new File(fileName));
		byte buffer[] = new byte[BUFFER_LEN];
		int count = 0;
		while (true) {
			count = fis.read(buffer, 0, BUFFER_LEN);
			if (count == -1) {
				break;
			}
			outMsg.write(buffer);

			if (count < BUFFER_LEN) {
				System.out.println("aaa");
			}
			outQueue.put(outMsg, pmo);
			outMsg.clearMessage();
		}
		fis.close();
	}

	public void runGoupSender() {
		try {
			init();
			sendMessages();
			qmgr.commit();
			System.out.println("\n Messages successfully Send ");
		} catch (MQException mqe) {
			mqe.printStackTrace();
			try {
				System.out.println("\n Backing out Transaction ");
				qmgr.backout();
				System.exit(2);
			} catch (Exception e) {
				e.printStackTrace();
				System.exit(2);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(2);
		}
	}

	/**
	 * ��������
	 * 
	 * @param args
	 */
	public static void main(String args[]) {
		MQFileSender mfs = new MQFileSender();
		int i = 0;
		while (true) {
			i++;
			System.out.println("" + i);
			mfs.runGoupSender();
			if (i == 1) {
				break;
			}
		}
	}
}
